package com.yitiao.socket.chatroom.demo;

import com.yitiao.socket.chatroom.CommonConst;
import lombok.SneakyThrows;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

public class AioClient {
    private AsynchronousSocketChannel channel;

    public static void main(String[] args) {
        AioClient client = new AioClient();
        client.start();
    }

    @SneakyThrows
    private void start() {
        channel = AsynchronousSocketChannel.open();
        Future<Void> connect = channel.connect(new InetSocketAddress(CommonConst.HOST, CommonConst.PORT));
        connect.get();

        System.out.println(channel.getLocalAddress());

        // 等待用户的输入
        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String input = consoleReader.readLine();

            byte[] inputBytes = input.getBytes();
            ByteBuffer buffer = ByteBuffer.wrap(inputBytes);
            Future<Integer> writeResult = channel.write(buffer);

            writeResult.get();
            buffer.flip();
            Future<Integer> readResult = channel.read(buffer);

            readResult.get();
            String echo = new String(buffer.array());
            buffer.clear();

            System.out.println(echo);
        }

    }
}
